package net.csdn.business.notify.handler.service.impl;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.csdn.business.notify.common.enums.NotifyChannel;
import net.csdn.business.notify.common.enums.NotifyType;
import net.csdn.business.notify.common.enums.ResultCodeEnum;
import net.csdn.business.notify.common.exception.BusinessException;
import net.csdn.business.notify.common.mapper.NotifyTemplateSetingMapper;
import net.csdn.business.notify.common.model.dto.NewNotifyTemplateSetingDTO;
import net.csdn.business.notify.common.model.dto.UpdateNotifyTemplateSetingDTO;
import net.csdn.business.notify.common.model.entity.NotifyTemplateSeting;
import net.csdn.business.notify.common.model.query.NotifyTemplateSetingQuery;
import net.csdn.business.notify.common.model.vo.NotifyBusinessVO;
import net.csdn.business.notify.common.model.vo.NotifyTemplateSetingVO;
import net.csdn.business.notify.common.pipeline.model.ContentModel;
import net.csdn.business.notify.handler.service.INotifyBusinessService;
import net.csdn.business.notify.handler.service.INotifyTemplateSetingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;



/**
 * 通知中心-模板配置Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-27
 */
@Service
public class NotifyTemplateSetingServiceImpl extends ServiceImpl<NotifyTemplateSetingMapper, NotifyTemplateSeting> implements INotifyTemplateSetingService
{

    @Autowired
    private INotifyBusinessService notifyBusinessService;

    /**
     * 分页查询通知中心-模板配置列表
     *
     * @param query 通知中心-模板配置
     * @return 通知中心-模板配置
     */
    @Override
    public Page<NotifyTemplateSetingVO> findPageList(NotifyTemplateSetingQuery query) {
        //获得Page对象
        Page<NotifyTemplateSetingVO> page = query.getPage();
        List<NotifyTemplateSetingVO> pageList=baseMapper.findPageList(page,query);
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询通知中心-模板配置
     * 
     * @param id 通知中心-模板配置主键
     * @return 通知中心-模板配置
     */
    @Override
    public NotifyTemplateSetingVO selectNotifyTemplateSetingById(Long id)
    {
        NotifyTemplateSetingVO result=baseMapper.selectNotifyTemplateSetingById(id);
        if(result==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        return result;
    }

    /**
     * 查询通知中心-模板配置列表
     * 
     * @param query 通知中心-模板配置
     * @return 通知中心-模板配置
     */
    @Override
    public List<NotifyTemplateSetingVO> selectNotifyTemplateSetingList(NotifyTemplateSetingQuery query)
    {
        return baseMapper.selectNotifyTemplateSetingList(query);
    }

    /**
     * 新增通知中心-模板配置
     *
     * @param params 通知中心-模板配置
     * @return 结果
     */
    @Override
    public Integer insertNotifyTemplateSeting(NewNotifyTemplateSetingDTO params)
    {
        String busCode=params.getBusinessCode();
        //判断业务编码是否存在
        NotifyBusinessVO businessVO=notifyBusinessService.selectNotifyBusinessByCode(busCode);
        if(businessVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"businessCode");
        }
        Long businessId=Long.parseLong(businessVO.getId());
        Integer notifyType=businessVO.getNotifyType();
        Integer notifyChannel=params.getNotifyChannel();
        if(notifyType== NotifyType.PRIVATE.getCode()&&notifyChannel!= NotifyChannel.IM.getCode()){
            throw new BusinessException(ResultCodeEnum.NOTIFY_BUSSINESS_CHANNEL_ERROR);
        }
        //根据业务编码和通道类型查询是否存在
        //判断修改后的编码是否存在
        LambdaQueryWrapper<NotifyTemplateSeting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NotifyTemplateSeting::getBusinessId, businessId);
        queryWrapper.eq(NotifyTemplateSeting::getNotifyChannel,notifyChannel);
        NotifyTemplateSeting notifyTemplate=baseMapper.selectOne(queryWrapper);
        if(notifyTemplate!=null){
            throw new BusinessException(ResultCodeEnum.NOTIFY_TEMPLATE_EXIST_ERROR);
        }
        NotifyTemplateSeting notifyTemplateSeting=new NotifyTemplateSeting();
        BeanUtils.copyProperties(params,notifyTemplateSeting);
        notifyTemplateSeting.setCreatedBy(params.getCurUserId());
        //配置模板内容，由于不同的通道模板需要的参数不一样，所以引入了json格式
        //根据模板预设字段，反射进行组装魔板的json结构，过滤多传的字段。
        JSONObject templatePre = params.getTemplate();
        JSONObject template = new JSONObject();
        Class<? extends ContentModel> contentModelClass = NotifyChannel.getChanelModelClassByCode(notifyChannel);
        Field[] fields = ReflectUtil.getFields(contentModelClass);
        for (Field field : fields) {
            String templateValue = templatePre.getString(field.getName());
            template.put(field.getName(),templateValue);
        }
        notifyTemplateSeting.setTemplate(template);
        return baseMapper.insert(notifyTemplateSeting);
    }

    /**
     * 修改通知中心-模板配置
     *
     * @param params 通知中心-模板配置
     * @return 结果
     */
    @Override
    public Integer updateNotifyTemplateSeting(UpdateNotifyTemplateSetingDTO params)
    {
        //根据id查询是否存在
        NotifyTemplateSetingVO notifyTemplateSetingVO=baseMapper.selectNotifyTemplateSetingById(params.getId());
        if(notifyTemplateSetingVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //判断业务编码是否存在
        //String busCode=notifyTemplateSetingVO.getBusinessId();
        Integer notifyChannel=params.getNotifyChannel();
        //根据业务编码和通道类型查询是否存在
        //判断修改后的编码是否存在
        /*LambdaQueryWrapper<NotifyTemplateSeting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NotifyTemplateSeting::getBusinessCode, busCode);
        queryWrapper.eq(NotifyTemplateSeting::getNotifyChannel,notifyChannel);
        queryWrapper.ne(NotifyTemplateSeting::getId,params.getId());
        NotifyTemplateSeting notifyTemplate=baseMapper.selectOne(queryWrapper);
        if(notifyTemplate!=null){
            throw new BusinessException(ResultCodeEnum.NOTIFY_TEMPLATE_EXIST_ERROR);
        }*/
        LambdaUpdateWrapper<NotifyTemplateSeting> updateWrapper = new UpdateWrapper<NotifyTemplateSeting>().lambda();
        updateWrapper.eq(NotifyTemplateSeting::getId, params.getId());
        NotifyTemplateSeting notifyTemplateSeting=new NotifyTemplateSeting();
        BeanUtils.copyProperties(params,notifyTemplateSeting);
        notifyTemplateSeting.setLastModifiedBy(params.getCurUserId());
        //根据模板预设字段，反射进行组装魔板的json结构，过滤多传的字段。
        JSONObject templatePre = params.getTemplate();
        JSONObject template = new JSONObject();
        Class<? extends ContentModel> contentModelClass = NotifyChannel.getChanelModelClassByCode(notifyChannel);
        Field[] fields = ReflectUtil.getFields(contentModelClass);
        for (Field field : fields) {
            String templateValue = templatePre.getString(field.getName());
            template.put(field.getName(),templateValue);
        }
        notifyTemplateSeting.setTemplate(template);
        return baseMapper.update(notifyTemplateSeting,updateWrapper);
    }


    /**
     * 删除通知中心-模板配置信息
     * 
     * @param id 通知中心-模板配置主键
     * @return 结果
     */
    @Override
    public Integer deleteNotifyTemplateSetingById(Long id)
    {
        //根据id查询是否存在
        NotifyTemplateSetingVO notifyTemplateSetingVO=baseMapper.selectNotifyTemplateSetingById(id);
        if(notifyTemplateSetingVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        return baseMapper.deleteNotifyTemplateSetingById(id);
    }
}
